<template>
  <div class="p-5">
    <n-form :model="form" ref="formRef" :label-width="80" :rules="rules" label-placement="left">
      <n-form-item label="用户名" path="">
        <n-input :disabled="true" v-model:value="user.username"/>
      </n-form-item>
      <n-form-item label="头像" path="avatar">
        <uploader v-model="form.avatar"/>
      </n-form-item>

      <n-form-item label="昵称" path="nickname">
        <n-input v-model:value="form.nickname" placeholder=""/>
      </n-form-item>

      <n-form-item label="性别" path="sex">
        <n-radio-group v-model:value="form.sex" name="sex">
          <n-space>
            <n-radio v-for="(item,index) in options" :key="index" :value="item.value" :label="item.value"/>
          </n-space>
        </n-radio-group>
      </n-form-item>

      <div class="flex justify-end">
        <n-button :loading="loading" type="primary" @click="onSubmit">提交修改</n-button>
      </div>
    </n-form>
  </div>
</template>

<script setup>
// 引入naive-ui
import {NForm, NFormItem, NInput, NRadio, NSpace, NRadioGroup, NButton, createDiscreteApi} from "naive-ui";

// 引入CompositionApi
import {ref, reactive} from "vue";

// 实例
const formRef = ref();

// 用户数据
const user = useUser()

// 表单数据
const form = reactive({
  avatar: "",
  nickname: "",
  sex: "",
});

// 初始化form
if (user.value) {
  form.avatar = user.value.avatar;
  form.nickname = user.value.nickname;
  form.sex = user.value.sex;
}


// 规则
const rules = {
  nickname: [
    {
      required: true,
      message: '昵称不能为空'
    }
  ],
  sex: [
    {
      required: true,
      message: '性别不能为空'
    }
  ]
}

// 选项
const options = [
  {
    value: "未知",
    label: ""
  },
  {
    value: "男",
    label: ""
  },
  {
    value: "女",
    label: ""
  }
];

// 表单loading
const loading = ref(false);
const onSubmit = () => {
  formRef.value.validate(async (errors) => {
    if (errors) return;
    loading.value = true;

    const {error} = await useUpdateUserInfoApi(form);

    loading.value = false;

    if (error.value) {
      return
    }


    const {message} = createDiscreteApi(['message']);
    message.success("修改成功");

    // 刷新用户信息
    await useRefreshUserInfo();

  })
}
</script>

<style scoped>

</style>